package com.kingsalert.kingsalert.fragment.main;

import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.FragmentActivity;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;
import androidx.viewpager2.widget.ViewPager2;

import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageButton;

import com.kingsalert.kingsalert.analytics.util.AnalyticsUtil;
import com.kingsalert.kingsalert.R;
import com.kingsalert.kingsalert.activity.ln.LnAplyActivity;
import com.kingsalert.kingsalert.activity.ln.MainActivity;
import com.kingsalert.kingsalert.activity.process.ProcessActivity;
import com.kingsalert.kingsalert.adapter.HomeCarouselAdapter;
import com.kingsalert.kingsalert.base.BaseLnFragment;
import com.kingsalert.kingsalert.bean.config.AppShowCustomize;
import com.kingsalert.kingsalert.bean.process.ProcessInfo;
import com.kingsalert.kingsalert.bean.userinfo.LnLimitInfo;
import com.kingsalert.kingsalert.config.PermissionConfig;
import com.kingsalert.kingsalert.config.UserState;
import com.kingsalert.kingsalert.dialog.CustomerServiceDialog;
import com.kingsalert.kingsalert.dialog.ProcessBottomDialog;
import com.kingsalert.kingsalert.util.UserInfoUtil;
import com.kingsalert.kingsalert.util.http.HttpUtil;

import java.util.ArrayList;
import java.util.List;

import pub.devrel.easypermissions.AppSettingsDialog;
import pub.devrel.easypermissions.EasyPermissions;

public class HomeFragment extends BaseLnFragment implements EasyPermissions.PermissionCallbacks,EasyPermissions.RationaleCallbacks{

    private final ArrayList<HomeCarouselAdapter.HomeCarouseInfo> homeCarouseInfos = new ArrayList<>();

    private ImageButton customerserviceIb;
    private ViewPager2 carouseViewpage2;
    private Button applyBtn;
    private View processView,dsView,contactusView;

    private Runnable processRunnable;

    private final Runnable applyRunnable = () -> {

        HttpUtil.getInstance().saveBuriedPoint(page,"APPLY_CLICK","");

        String[] homePermissions = AppShowCustomize.getInstance().getHomePermission();

        if (PermissionConfig.checkPermissions(requireActivity(), homePermissions)) {
            //device info upload
            try {
                if (UserInfoUtil.getInstance().didLogin()) {
                    AnalyticsUtil.INSTANCE.saveDeviceS2SInfo();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }

            //申请流程
            processRunnable = () -> {
                //无流程：跳转到申请页
                if (ProcessInfo.getInstance().getSteps().isEmpty())
                    startActivity(new Intent(requireActivity(), LnAplyActivity.class));
                //有流程：跳转到流程页
                else startActivity(new Intent(requireContext(), ProcessActivity.class));
            };

            HttpUtil.getInstance().userProcess(requireActivity(),this::onUserProcessResponse);

        } else {
            EasyPermissions.requestPermissions(this, getString(R.string.launch_permissions_all), PermissionConfig.PermissionCode_Home, homePermissions);
        }

    };

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        page = "HOME";
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_home, container, false);

        customerserviceIb = view.findViewById(R.id.fh_ib_customerservice);
        carouseViewpage2 = view.findViewById(R.id.fh_viewpage2);
        applyBtn = view.findViewById(R.id.fh_btn_apply);
        processView = view.findViewById(R.id.fh_view_process);
        dsView = view.findViewById(R.id.fh_view_ds);
        contactusView = view.findViewById(R.id.fh_view_contactus);

        SwipeRefreshLayout refreshLayout = view.findViewById(R.id.fh_refreshlayout);
        refreshLayout.setOnRefreshListener(() -> {
            HttpUtil.getInstance().saveBuriedPoint(page,"REFRESH_CLICK","");
            refreshLayout.setRefreshing(false);
            HttpUtil.getInstance().userProcess(requireActivity(),this::onUserProcessResponse);
        });

        initView();

        return view;
    }

    @Override
    public void onResume() {
        super.onResume();
        HttpUtil.getInstance().requestLnLimit(requireActivity(),this::onLnLimitResponse);
    }

    private void initCarouse(){
        homeCarouseInfos.clear();

        homeCarouseInfos.add(new HomeCarouselAdapter.HomeCarouseInfo(LnLimitInfo.getInstance().getLimitAmount(), false));
        homeCarouseInfos.addAll(LnLimitInfo.getInstance().getHomeCarouseInfos());

        HomeCarouselAdapter homeCarouselAdapter = new HomeCarouselAdapter(requireContext(),homeCarouseInfos);
        carouseViewpage2.setAdapter(homeCarouselAdapter);

        new Thread(() -> {
            int count=0;
            while (++count<Integer.MAX_VALUE){
                try {
                    Thread.sleep(1992);
                    int nextIndex = carouseViewpage2.getCurrentItem()+1;
                    if (nextIndex<Integer.MAX_VALUE-2)
                        requireActivity().runOnUiThread(() -> carouseViewpage2.setCurrentItem(nextIndex));
                    Thread.sleep(2814);
                } catch (InterruptedException|IllegalStateException e) {
                    e.printStackTrace();
                    break;
                }
            }
        }).start();

    }

    private void initView(){

        customerserviceIb.setOnClickListener(v -> new CustomerServiceDialog(requireContext()).show());
        contactusView.setOnClickListener(v -> new CustomerServiceDialog(requireContext()).show());

        //申请
        applyBtn.setOnClickListener(v -> applyRunnable.run());

        processView.setOnClickListener(v -> {
            processRunnable = () -> new ProcessBottomDialog(requireContext(),applyRunnable).show();
            HttpUtil.getInstance().userProcess(requireActivity(),this::onUserProcessResponse);
        });

        dsView.setOnClickListener(v -> {
            String agreementUrl = AppShowCustomize.getInstance().getAgreementUrl();
            if (TextUtils.isEmpty(agreementUrl)) return;
            startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(agreementUrl)));
        });

    }

    public void onUserProcessResponse(){
        String state = ProcessInfo.getInstance().getUserState();
        if (UserState.isStateChange(state)) {//刷新用户状态
            FragmentActivity activity = requireActivity();
            UserState.clearState();
            activity.startActivity(new Intent(activity, MainActivity.class));
            activity.finish();
        }else if (processRunnable!=null) {
            processRunnable.run();
            processRunnable = null;
        }else HttpUtil.getInstance().requestLnLimit(requireActivity(),this::onLnLimitResponse);
    }

    public void onLnLimitResponse(){
        initCarouse();
    }

    @Override
    public void onPermissionsGranted(int requestCode, @NonNull List<String> perms) {
        applyRunnable.run();
    }

    @Override
    public void onPermissionsDenied(int requestCode, @NonNull List<String> perms) {
        if (EasyPermissions.somePermissionPermanentlyDenied(this,perms))
            new AppSettingsDialog.Builder(this).build().show();
    }

    @Override
    public void onRationaleAccepted(int requestCode) {}

    @Override
    public void onRationaleDenied(int requestCode) {}

}